package org.sbbs.app.security.dao.hibernate;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.sbbs.app.security.dao.RoleDao;
import org.sbbs.app.security.model.Role;
import org.sbbs.base.dao.hibernate.BaseDaoHibernate;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

@Repository("roleDao")
public class RoleDaoHibernate extends BaseDaoHibernate<Role, Long>
		implements
			RoleDao {

	public RoleDaoHibernate() {
		super(Role.class);
	}

	@Override
	public List<Role> getRolesByUserId(Long userId) {

		return (List) this.getHibernateTemplate().execute(
				new RolesByUserIdCallBack(userId));
	}

}

class RolesByUserIdCallBack implements HibernateCallback {
	Long userId;

	RolesByUserIdCallBack(Long uid) {
		this.userId = uid;
	}

	@Override
	public Object doInHibernate(Session session) throws HibernateException,
			SQLException {
		String hql = "SELECT a.* from t_role a JOIN user_role b ON a.id=b.role_id where b.user_id=?";
		Query q = session.createSQLQuery(hql).addEntity(Role.class);
		q.setParameter(0, userId);

		return q.list();
	}

}
